<template>
	<view class="container">
		<view class='wrapper'>
			<view class="img-list">
				<view class="img-item" v-for="(item, index) in imgList" :key="index">
					<image :src="item" @click="previewImgae(index)" mode="aspectFill"></image>
				</view>
				<view class="img-item">
					<view class="upload">
						<view class="img-icon" @click="chooseImg">
							<tui-icon name="plus"></tui-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="title">
				<view class="uni-textarea">
					<textarea @blur="bindTextAreaBlur" auto-height placeholder-style="color:#bebebe"
						placeholder="请输入标题..." maxlength=20 style="font-size: 36px;" v-model="titleContent" />
				</view>
			</view>
			<view class='toolbar' @tap="format">
				<!-- 粗体 -->
				<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold">
				</view>
				<!-- 斜体 -->
				<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic">
				</view>
				<!-- 下划线 -->
				<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
					data-name="underline"></view>
				<!-- 画横线 -->
				<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian"
					data-name="strike"></view>
				<!-- 左靠齐 -->
				<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi"
					data-name="align" data-value="left"></view>
				<!-- 居中 -->
				<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi"
					data-name="align" data-value="center"></view>
				<!-- 右靠齐 -->
				<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi"
					data-name="align" data-value="right"></view>
				<!-- 左右对齐 -->
				<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi"
					data-name="align" data-value="justify"></view>
				<!-- 行高 -->
				<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height"
					data-name="lineHeight" data-value="2"></view>
				<!-- 字母间距 -->
				<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing"
					data-name="letterSpacing" data-value="2em"></view>


				<!-- 上对齐 -->
				<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju"
					data-name="marginTop" data-value="20px"></view>
				<!-- 下对齐 -->
				<view :class="formats.previewarginBottom ? 'ql-active' : ''" class="iconfont icon-723bianjiqi_duanhouju"
					data-name="marginBottom" data-value="20px"></view>


				<!-- 字体 -->
				<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font" data-name="fontFamily"
					data-value="Pacifico"></view>
				<!-- 字体大小 -->
				<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize"
					data-name="fontSize" data-value="24px"></view>
				<!-- 字体颜色 -->
				<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color"
					data-name="color" data-value="#0000ff"></view>
				<!-- 字体背景颜色-->
				<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
					class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00"></view>
				<!-- 清单 -->
				<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
				<!-- 有序列表 -->
				<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie"
					data-name="list" data-value="ordered"></view>
				<!-- 无序列表 -->
				<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
					data-name="list" data-value="bullet"></view>
				<!-- 减少缩进 -->
				<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
				<!-- 增加缩进 -->
				<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
				<!-- 标题 -->
				<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1"
					data-name="header" :data-value="1"></view>
				<!-- 字体下标 -->
				<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao"
					data-name="script" data-value="sub"></view>
				<!-- 字体上标 -->
				<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao"
					data-name="script" data-value="super"></view>
				<!-- 文本方向右 -->
				<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl"
					data-name="direction" data-value="rtl"></view>
				<!-- 插入分割线 -->
				<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
				<!-- 清除格式 -->
				<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>
				<!-- 插入图片 -->
				<view class="iconfont icon-charutupian" @tap="insertImage"></view>
				<!-- 日历 -->
				<view class="iconfont icon-date" @tap="insertDate"></view>
				<!-- 清空 -->
				<view class="iconfont icon-shanchu" @tap="clear"></view>
				<!-- 撤销 -->
				<view class="iconfont icon-undo" @tap="undo"></view>
				<!-- 恢复 -->
				<view class="iconfont icon-redo" @tap="redo"></view>
			</view>

		</view>
		<view class="main">
			<view class="content">
				<editor id="editor" class="ql-container" placeholder="开始输入..." showImgSize showImgToolbar showImgResize
					@statuschange="onStatusChange" :read-only="false" @ready="onEditorReady" @blur="getContents">
				</editor>
			</view>
			<view class="tag">
				<view class="icon">
					<tui-icon name="bankcard"></tui-icon>
					<p>选择分区</p>
				</view>
				<view class="tag-item">
					{{ imgInfo.categoryStr }}
				</view>
				<view class="right">
					<view @click="show"><tui-icon name="arrowright"></tui-icon></view>
				</view>
			</view>

			<view class="tag">
				<view class="icon">
					<tui-icon name="label"></tui-icon>
					<p>添加标签</p>
				</view>
				<view class="tag-item">
					{{ tagcontent }}
				</view>
				<view class="right">

					<view @click="nextAddTag">
						<tui-icon name="arrowright"></tui-icon>
					</view>
				</view>
			</view>
		</view>
		<button @click="save">保存</button>
		<div v-html="richText"></div>
		<div>
			<div>
				<img v-for="(image, index) in imgList" :key="index" :src="image" alt="uploaded image"
					class="responsive-image">
			</div>
		</div>
		<tui-toast ref="toast"></tui-toast>

		<!-- 底部弹出 -->
		<tui-bottom-popup :zIndex="1002" :maskZIndex="1001" :show="popupShow" @close="popup">
			<view class="categoryBox">

				<view class="category-left">
					<scroll-view scroll-y style="height: 500rpx;">
						<tui-list-view color="#777">
							<tui-list-cell v-for="(category, index) in categoryList" :key="index"
								@click="getCategoryTwo(category)">
								<view>{{ category.name }}</view>
							</tui-list-cell>
						</tui-list-view>
					</scroll-view>
				</view>

				<view class="category-right">
					<scroll-view scroll-y style="height: 500rpx;">
						<tui-list-view color="#777">
							<tui-list-cell v-for="(category, index) in categoryOne.children" :key="index"
								@click="getCategoryInfo(category)">
								<view class="title">{{ category.name }}</view>
								<view class="desc">{{ category.description }}</view>
							</tui-list-cell>
						</tui-list-view>
					</scroll-view>
				</view>
			</view>
		</tui-bottom-popup>

		<!-- 弹框 -->
		<tui-modal :show="modal" @click="handleClick" @cancel="hide" content="退出数据将不会保存" color="#333" :size="32"
			shape="circle"></tui-modal>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				flag: 0, //标志是否是新建笔记
				// richText: '<p><strong>你好！</strong></p>',
				richText: '',
				titleContent: "",
				formats: {},
				timer: null,
				editorDetail: "",
				popupShow: false,
				imgList: [],
				imgInfo: {},
				imgsUrl: '',
				tagList: [],
				tagcontent: '',
				categoryList: [],
				categoryOne: {},
				categoryArr: [],
				modal: false,
				type: 'add',
				mid: '',
				version: 0,
			}
		},
		created() {
			const storedImgList = uni.getStorageSync("imgList");
			if (storedImgList) {
				this.imgList = JSON.parse(storedImgList);
			}
		},
		onLoad(option) {
			this.flag = option.flag
			console.log(this.flag)
			if (option.mid != null && option.type != null && option.version == 0) {
				this.mid = option.mid
				this.type = option.type
				this.getOne(this.mid)
			} else {
				this.mid = option.mid
				this.type = option.type
			}
		},
		onShow() {
			// this.getTagContent()
		},
		// created() {
		// 	this.imgList = JSON.parse(uni.getStorageSync("imgList"))
		// },
		onBackPress(options) {
			/**
			 * 由于 uni.navigateBack() 同样会触发 onBackPress 函数。
			 * 因此在 onBackPress 中直接调用 uni.navigateBack() 并始终返回 true 会引发死循环。
			 * 此时，需要根据onBackPress的回调对象中的from值来做处理，当来源是'navigateBack'时，返回 false 。
			 */
			// console.log("----------onBackPress---------", options)
			if (options.from === 'navigateBack') {
				return false;
			}
			this.back();
			return true;
		},
		mounted() {
			this.onEditorReady();
			// 将数据渲染到富文本内
			this.timer = setInterval(() => {
				if (this.editorDetail) {
					clearInterval(this.timer)
					this.editorCtx.setContents({
						html: this.editorDetail,
						success(res) {
							// console.log(res);
						}
					})
				}
			}, 100)
		},

		methods: {
			save() {
				// 在这里保存textarea的输入内容至全局数据对象
				// this.$options.globalData.textareaContent = this.textareaContent;
				// 跳转到目标页面
				// uni.navigateTo({
				//   url: '../../pages/normalNote/normalNote'
				// });
				// uni.setStorageSync('textareaContent', this.textareaContent);
				// 将that.imgInfo对象转换为JSON字符串，并将其保存在名为imgInfo的本地存储中
				// uni.setStorageSync('imgInfo', JSON.stringify(that.imgInfo))
				// 后续可以使用uni.getStorageSync('imgInfo')来获取保存的数据。

				var that = this
				const value = that.titleContent;
				// 打印标题
				console.log(value);
				this.editorCtx.getContents({
					success(res) {
						// debugger
						that.tempDelta = res.delta
						// 打印内容并显示在最下面
						console.log(res)
						that.richText = res.html;
					}
				})


			},
			// 失去焦点时触发，获取富文本的内容
			getContents() {
				let _this = this
				this.editorCtx.getContents({
					success(res) {
						_this.$emit('getContents', res.html)
					}
				})
			},
			//编辑框初始化时触发
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context;
				}).exec()
			},
			//撤销
			undo() {
				this.editorCtx.undo()
			},
			//恢复
			redo() {
				this.editorCtx.redo()
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				this.editorCtx.format(name, value)

			},
			//通过 Context 方法改变编辑器内样式时触发，返回选区已设置的样式
			onStatusChange(e) {
				this.formats = e.detail
				console.log(e);
			},
			//插入分隔符
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			//清空全部内容
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						console.log("clear success")
					}
				})
			},
			//清除样式
			removeFormat() {
				this.editorCtx.removeFormat()
			},
			//插入当前日期
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDate
				})
			},
			//插入图片
			insertImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.editorCtx.insertImage({
							src: res.tempFilePaths[0],
							alt: '图像',
							success: function() {
								console.log('insert image success')
							}
						})
					}
				})
			},
			back() {
				this.modal = true
			},
			handleClick(e) {
				let index = e.index;
				if (index == 1) {
					uni.removeStorageSync("imgList")
					uni.removeStorageSync("tags")
					uni.removeStorageSync("imgInfo")
					uni.switchTab({
						url: "/pages/normalNote/normalNote"
					})
				}
				this.hide();
			},
			hide() {
				this.modal = false
			},
			show() {
				this.popupShow = true
				getCategory().then(res => {

					this.categoryList = res.data
				})
			},

			chooseImg() {
				let that = this

				if (that.imgList.length >= 9) {
					uni.showToast({
						title: "图片上限"
					})
					return
				}
				let maxCount = 9 - that.imgList.length
				uni.chooseImage({
					count: maxCount, // 最多可以选择的图片张数，默认9
					sizeType: ['original'], //original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					success: function(res) {
						that.imgList.push(...res.tempFilePaths)
						uni.setStorageSync("imgList", JSON.stringify(that.imgList))
					}
				})
			},

			previewImgae(index) {
				let that = this
				uni.previewImage({
					current: index, // 当前显示图片的索引值
					urls: that.imgList, // 需要预览的图片列表，photoList要求必须是数组
					longPressActions: {
						itemList: ['删除'],
						success: function(data) {

							that.imgList.splice(data.index, 1)
							uni.setStorageSync("imgList", JSON.stringify(that.imgList))
							uni.closePreviewImage()
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},

			getCategoryTwo(category) {
				this.categoryOne = category
				this.categoryArr[0] = category.name
			},
			getCategoryInfo(category) {

				this.categoryArr[1] = category.name
				this.imgInfo.categoryId = category.id
				this.imgInfo.categoryPid = category.pid
				this.popupShow = false
				this.imgInfo.categoryStr = this.categoryArr[0] + '-' + this.categoryArr[1]
			},
			popup() {
				this.popupShow = false
			},
			// getTagContent() {
			// 	let that = this
			// 	that.tagList = JSON.parse(uni.getStorageSync('tags'))
			// 	that.imgInfo = JSON.parse(uni.getStorageSync("imgInfo"))
			// 	let str = ''

			// 	for (let i = 0; i < that.tagList.length; i++) {
			// 		str += '#' + that.tagList[i].name
			// 	}
			// 	that.tagcontent = str
			// },
			// nextAddTag() {

			// 	//这两行非常重要
			// 	this.imgInfo.tags = this.tagList
			// 	uni.setStorageSync('imgInfo', JSON.stringify(this.imgInfo))

			// 	if (this.type == 'update') {

			// 		uni.navigateTo({
			// 			url: "/pages/addtag/addtag?mid=" + this.mid + '&type=update'
			// 		})

			// 	} else {
			// 		uni.navigateTo({
			// 			url: "/pages/addtag/addtag?mid=" + this.mid + '&type=add'
			// 		})
			// 	}
			// },

			// ---------------编辑操作
			// getOne(mid) {
			// 	let params = {
			// 		id: mid
			// 	}
			// 	getOne(params).then(res => {

			// 		this.imgInfo = res.data
			// 		this.imgList = res.data.imgsUrl
			// 		this.tagList = res.data.tagList
			// 		this.imgInfo.categoryStr = res.data.categoryPName + '-' + res.data.categoryName;

			// 		uni.setStorageSync('tags', JSON.stringify(this.tagList))
			// 		uni.setStorageSync('imgList', JSON.stringify(this.imgList))
			// 		let str = ''

			// 		for (let i = 0; i < this.tagList.length; i++) {
			// 			str += '#' + this.tagList[i].name
			// 		}
			// 		this.tagcontent = str

			// 	})
			// },

			next() {
				let that = this
				let userInfo = uni.getStorageSync("userInfo")

				if (userInfo.username == null) {
					let params = {
						title: "请先登录",
					}
					that.$refs.toast.show(params);
				} else {


					if (typeof that.imgInfo.content == 'undefined' || that.imgInfo.content == '') {
						let params = {
							title: "请输入内容",
						}
						that.$refs.toast.show(params);
					} else if (typeof that.imgInfo.categoryStr == 'undefined' || that.imgInfo.categoryStr == '') {
						let params = {
							title: "请选择一个分区",
						}
						that.$refs.toast.show(params);
					} else {
						uni.getStorage({
							key: 'tags',
							success: function(res) {
								that.tagList = JSON.parse(res.data)
							}
						})

						that.imgInfo.userId = userInfo.id
						that.imgInfo.tags = that.tagList

						uni.setStorageSync('imgInfo', JSON.stringify(that.imgInfo))

						uni.navigateTo({
							url: '/pages/addalbum/addalbum?type=' + that.type
						})
					}
				}
			},

		}
	}
</script>

<style scoped>
	@import url('others.css');
	@import url('https://cdn.jsdelivr.net/npm/tui-modal/dist/tui-modal.css');

	.uni-textarea {}



	.responsive-image {
		display: flex;
		flex-wrap: wrap;
		width: 100%;
		height: auto;
		object-fit: cover;
		margin-bottom: 10px;
	}

	.wrapper {
		padding: 5px;
	}

	.iconfont {
		display: inline-block;
		padding: 10px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
		background-color: #ffffff;
		position: -webkit-sticky;
		position: sticky;
		top: var(--window-top);
		z-index: 99;
		height: 95px;
	}

	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		min-height: 30vh;
		height: auto;
		background: #fff;
		margin-top: 10px;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}
</style>